package com.cong.ele.task;

import com.cong.ele.conf.GanFanRenConf;
import com.cong.ele.param.GanFan;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author cong.zheng
 * @since 2021/6/15 18:04
 */
@Component
@EnableScheduling
@EnableAsync
@Slf4j
public class DingCanTask {

    private static final String HOST_URL = "http://chifan.taimei.com/";

    @Autowired
    private GanFanRenConf ganFanRenConf;

    // 0 0 11 ? * 2-6 *
    @Scheduled(cron = "0 0 10 * * 1,2,3,4,5")
    public void ganFan() {
        ganFanRenConf.getGanFanList().forEach(this::doGanFan);

    }

    public void doGanFan(GanFan ganFan) {
        log.info("{}开始干饭", ganFan.getUsername());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username", ganFan.getUsername());
        map.add("password", ganFan.getPassword());
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, httpHeaders);
        ResponseEntity<String> postForEntity = new RestTemplate().postForEntity(HOST_URL + "login", httpEntity,
                String.class);
        log.info(postForEntity.getBody());
        // 保存jsession
        HttpHeaders headers = postForEntity.getHeaders();
        List<String> list = headers.get("Set-Cookie");
        if (list == null || list.isEmpty()) {
            log.error("获取cookie失败");
            return;
        }
        HttpHeaders ahttpHeaders = new HttpHeaders();
        ahttpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        ahttpHeaders.put(HttpHeaders.COOKIE, list);
        LinkedMultiValueMap<String, String> addMap = new LinkedMultiValueMap<>();
        addMap.add("city", ganFan.getCity());
        addMap.add("phone", ganFan.getPhone());
        HttpEntity<MultiValueMap<String, String>> httpEntity2 = new HttpEntity<>(addMap, ahttpHeaders);

        ResponseEntity<String> postForEntity2 = new RestTemplate().postForEntity(HOST_URL + "module/dinner/add",
                httpEntity2, String.class);
        log.info(postForEntity2.getBody());
    }

}
